package com.emapp.lccode.utils

import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.afollestad.materialdialogs.LayoutMode
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.WhichButton
import com.afollestad.materialdialogs.actions.getActionButton
import com.afollestad.materialdialogs.bottomsheets.BottomSheet
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.hjq.toast.Toaster
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException

/**
 * @param message 显示对话框的内容 必填项
 * @param title 显示对话框的标题 默认 温馨提示
 * @param positiveButtonText 确定按钮文字 默认确定
 * @param positiveAction 点击确定按钮触发的方法 默认空方法
 * @param negativeButtonText 取消按钮文字 默认空 不为空时显示该按钮
 * @param negativeAction 点击取消按钮触发的方法 默认空方法
 *
 */
fun AppCompatActivity.showMessage(
    message: String,
    title: String = "温馨提示",
    positiveButtonText: String = "确定",
    positiveAction: () -> Unit = {},
    negativeButtonText: String = "",
    negativeAction: () -> Unit = {}
) {
    MaterialDialog(this)
        .cancelable(true)
        .lifecycleOwner(this)
        .show {
            title(text = title)
            message(text = message)
            positiveButton(text = positiveButtonText) {
                positiveAction.invoke()
            }
            if (negativeButtonText.isNotEmpty()) {
                negativeButton(text = negativeButtonText) {
                    negativeAction.invoke()
                }
            }
            getActionButton(WhichButton.POSITIVE).updateTextColor(SettingUtil.getColor(this@showMessage))
            getActionButton(WhichButton.NEGATIVE).updateTextColor(SettingUtil.getColor(this@showMessage))
        }
}

/**
 * @param message 显示对话框的内容 必填项
 * @param title 显示对话框的标题 默认 温馨提示
 * @param positiveButtonText 确定按钮文字 默认确定
 * @param positiveAction 点击确定按钮触发的方法 默认空方法
 * @param negativeButtonText 取消按钮文字 默认空 不为空时显示该按钮
 * @param negativeAction 点击取消按钮触发的方法 默认空方法
 */
fun Fragment.showMessage(
    message: String,
    title: String = "温馨提示",
    positiveButtonText: String = "确定",
    positiveAction: () -> Unit = {},
    negativeButtonText: String = "",
    negativeAction: () -> Unit = {}
) {
    activity?.let {
        MaterialDialog(it)
            .cancelable(true)
            .lifecycleOwner(viewLifecycleOwner)
            .show {
                title(text = title)
                message(text = message)
                positiveButton(text = positiveButtonText) {
                    positiveAction.invoke()
                }
                if (negativeButtonText.isNotEmpty()) {
                    negativeButton(text = negativeButtonText) {
                        negativeAction.invoke()
                    }
                }
                getActionButton(WhichButton.POSITIVE).updateTextColor(SettingUtil.getColor(it))
                getActionButton(WhichButton.NEGATIVE).updateTextColor(SettingUtil.getColor(it))
            }


//        MaterialDialog(it, BottomSheet(LayoutMode.WRAP_CONTENT)).lifecycleOwner(viewLifecycleOwner)
//            .show {
//                title(text = title)
//                message(text = message)
//                positiveButton(text = positiveButtonText) {
//                    positiveAction.invoke()
//                }
//                if (negativeButtonText.isNotEmpty()) {
//                    negativeButton(text = negativeButtonText) {
//                        negativeAction.invoke()
//                    }
//                }
//
//            }
    }
}
/**
 *  MaterialDialog(this).show {
title(text = "输入数量")
input(
hint = "请输入内容",
inputType= InputType.TYPE_CLASS_NUMBER,
waitForPositiveButton = true

) { dialog, input ->
val inputValue = input.toString()
var n=inputValue.toIntOrNull()
if (n==null){
Toaster.show("请填写数字")
}else{
mates[position].use_num=n
materialAdapter.notifyDataSetChanged()
}
}
positiveButton(text = "确认")
negativeButton(text = "取消")
}


var d = it.data.map { re -> re.name }.toList()
MaterialDialog(this@DeviceAddKtActivity).show {
cancelable(true)
lifecycleOwner(this@DeviceAddKtActivity)
listItems(null, d,null,true) { _, index, text ->
mViewBind.tvProject.text = it.data[index].itemLabel
infor?.project_id = it.data[index].id
}
}


R.id.bottomsheet_info.onClickDebounced {
MaterialDialog(this, BottomSheet(WRAP_CONTENT)).show {
title(R.string.useGoogleLocationServices)
message(R.string.useGoogleLocationServicesPrompt)
positiveButton(R.string.agree)
negativeButton(R.string.disagree)
debugMode(debugMode)
lifecycleOwner(this@MainActivity)
}
}

R.id.bottomsheet_list.onClickDebounced {
MaterialDialog(this, BottomSheet(WRAP_CONTENT)).show {
listItems(R.array.states) { _, index, text ->
toast("Selected item $text at index $index")
}
positiveButton(R.string.agree)
negativeButton(R.string.disagree)
debugMode(debugMode)
lifecycleOwner(this@MainActivity)
}
}

R.id.bottomsheet_grid.onClickDebounced {
val items = listOf(
BasicGridItem(R.drawable.ic_icon_android, "One"),
BasicGridItem(R.drawable.ic_icon_android, "Two"),
BasicGridItem(R.drawable.ic_icon_android, "Three"),
BasicGridItem(R.drawable.ic_icon_android, "Four"),
BasicGridItem(R.drawable.ic_icon_android, "Five"),
BasicGridItem(R.drawable.ic_icon_android, "Six"),
BasicGridItem(R.drawable.ic_icon_android, "Seven"),
BasicGridItem(R.drawable.ic_icon_android, "Eight")
)

MaterialDialog(this, BottomSheet(WRAP_CONTENT)).show {
gridItems(items) { _, index, item ->
toast("Selected item ${item.title} at index $index")
}
positiveButton(R.string.agree)
negativeButton(R.string.disagree)
debugMode(debugMode)
lifecycleOwner(this@MainActivity)
}
}

R.id.bottomsheet_customView.onClickDebounced {
showCustomViewDialog(BottomSheet(WRAP_CONTENT))
}

R.id.bottomsheet_colorPicker.onClickDebounced {
MaterialDialog(this, BottomSheet(WRAP_CONTENT)).show {
title(R.string.custom_colors_argb)
colorChooser(
colors = ColorPalette.Primary,
subColors = ColorPalette.PrimarySub,
allowCustomArgb = true,
showAlphaSelector = true
) { _, color ->
toast("Selected color: ${color.toHex()}")
}
positiveButton(R.string.select)
negativeButton(android.R.string.cancel)
debugMode(debugMode)
lifecycleOwner(this@MainActivity)
}
}

R.id.bottomsheet_dateTimePicker.onClickDebounced {
MaterialDialog(this, BottomSheet(WRAP_CONTENT)).show {
title(text = "Select Date and Time")
dateTimePicker(requireFutureDateTime = true) { _, dateTime ->
toast("Selected date/time: ${dateTime.formatDateTime()}")
}
lifecycleOwner(this@MainActivity)
debugMode(debugMode)
}
}
}


//                    MaterialDialog(this@ProjectMapActivity).show {
//                        cancelable(true)
//                        lifecycleOwner(this@ProjectMapActivity)
//                        title(text = "创建工程选择")
//                        listItemsSingleChoice(
//                            null,
//                            listOf("打点", "录制轨迹"),
//                            null,
//                            0
//                        ) { _, index, text ->
//                            Toaster.show(text)
//                            if (index == 0) {
//
//                            } else {
//                                mViewBind.tvAdd.visibility = View.GONE
//                                mViewBind.fvStart.visibility = View.VISIBLE
//                                mViewBind.ivStart.visibility = View.VISIBLE
//                                mViewBind.ivEnd.visibility = View.GONE
//                                mViewBind.ivDelete.visibility = View.VISIBLE
//                            }
//                        }
//                        positiveButton(text = "确认")
//                    }
 */
/**
 * 获取进程号对应的进程名
 *
 * @param pid 进程号
 * @return 进程名
 */
fun getProcessName(pid: Int): String? {
    var reader: BufferedReader? = null
    try {
        reader = BufferedReader(FileReader("/proc/$pid/cmdline"))
        var processName = reader.readLine()
        if (!TextUtils.isEmpty(processName)) {
            processName = processName.trim { it <= ' ' }
        }
        return processName
    } catch (throwable: Throwable) {
        throwable.printStackTrace()
    } finally {
        try {
            reader?.close()
        } catch (exception: IOException) {
            exception.printStackTrace()
        }

    }
    return null
}

/**
 * 加入qq聊天群
 */
fun Fragment.joinQQGroup(key: String): Boolean {
    val intent = Intent()
    intent.data =
        Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D$key")
    // 此Flag可根据具体产品需要自定义，如设置，则在加群界面按返回，返回手Q主界面，不设置，按返回会返回到呼起产品界面    //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    return try {
        startActivity(intent)
        true
    } catch (e: Exception) {
        // 未安装手Q或安装的版本不支持
        Toaster.show("未安装手机QQ或安装的版本不支持")
        false
    }
}

/**
 * 拦截登录操作，如果没有登录跳转登录，登录过了贼执行你的方法
 */
//fun NavController.jumpByLogin(action: (NavController) -> Unit) {
//    if (CacheUtil.isLogin()) {
//        action(this)
//    } else {
//        this.navigateAction(R.id.action_to_loginFragment)
//    }
//}

/**
 * 拦截登录操作，如果没有登录执行方法 actionLogin 登录过了执行 action
 */
//fun NavController.jumpByLogin(
//    actionLogin: (NavController) -> Unit,
//    action: (NavController) -> Unit
//) {
//    if (CacheUtil.isLogin()) {
//        action(this)
//    } else {
//        actionLogin(this)
//    }
//}


fun List<*>?.isNull(): Boolean {
    return this?.isEmpty() ?: true
}

fun List<*>?.isNotNull(): Boolean {
    return this != null && this.isNotEmpty()
}

/**
 * 根据索引获取集合的child值
 * @receiver List<T>?
 * @param position Int
 * @return T?
 */
inline fun <reified T> List<T>?.getChild(position: Int): T? {
    //如果List为null 返回null
    return if (this == null) {
        null
    } else {
        //如果position大于集合的size 返回null
        if (position + 1 > this.size) {
            null
        } else {
            //返回正常数据
            this[position]
        }
    }
}

